import got from "got";
import qs from "qs";
import { encryption } from "../../utils/encryption";

// import tunnel from "tunnel";
// const tunnelingAgent = tunnel.httpOverHttp({
//   proxy: {
//     host: "localhost",
//     port: 8888,
//   },
// });

// 获取初始 token 等全局变量
const authorization = process.env.ICAN_AUTHORIZATION;
const prefixUrl = process.env.IEP_PREFIXURL;
const loginPath = process.env.ICAN_LOGIN_PATH;

const headers = {
  authorization,
};

const loginUrl = `${prefixUrl}${loginPath}`;
const login = async (
  username: string,
  password: string,
  code: string,
  randomNum: string
) => {
  const form = {
    username,
    password,
    randomStr: randomNum,
    code,
  };
  const formData = {
    ...encryption({
      data: form,
      param: ["password"],
    }),
    grant_type: "password",
    scope: "server",
  };
  const params = qs.stringify(formData);
  const url = `${loginUrl}?${params}`;
  try {
    const res = await got.post(url, {
      method: "POST",
      headers,
      // agent: {
      //   http: tunnelingAgent,
      // },
    });
    return res;
  } catch (error) {
    console.error(error);
  }
};

export { login };
